<template>
  <el-form :model="form" label-width="60px">
    <el-form-item label="用户名">
      <el-input v-model="form.username" />
    </el-form-item>
    <el-form-item label="密码">
      <el-input v-model="form.password" type="password" />
    </el-form-item>
    <el-form-item>
      <el-checkbox v-model="rememberMe" label="记住密码" size="large" @change="change"/>
    </el-form-item>
    <el-form-item>
      <el-button type="primary" @click="onSubmit" style="width: 100%">登录</el-button>
    </el-form-item>
  </el-form>
</template>

<script lang="ts" setup>
import { ref,reactive ,onMounted} from 'vue'
import { ElMessage } from 'element-plus'
import { useRouter } from 'vue-router'
const router = useRouter()

// do not use same name with ref
const form = reactive({
  username: '',
  password: ''
})

const rememberMe = ref(false)

onMounted(() => {
  // 获取本地存储的数据
  const rememberMeValue = localStorage.getItem('rememberMe');
  rememberMe.value = rememberMeValue === 'true';
  const userinfo = localStorage.getItem('userinfo');

  if (rememberMeValue === 'true' && userinfo) {
    const userinfoObj = JSON.parse(userinfo);
    form.username = userinfoObj.username;
    form.password = userinfoObj.password;
  }

})

const onSubmit = async () => {
  let res = await window.db.select(
    'select * from user where username = ? and password = ?',
    form.username,
    form.password
  )
  if (res.length > 0) {
    // 存储数据
    if(rememberMe.value){
      localStorage.setItem('rememberMe', 'true');
      localStorage.setItem('userinfo', JSON.stringify(form));
      sessionStorage.setItem('username', form.username);
    }
    
    router.push({ path: '/xwbl' })
    window.operation.maximize()
  } else {
    ElMessage.error('用户名或密码错误！')
  }
}

const change = () => {
  if (!rememberMe.value) {
    localStorage.removeItem('rememberMe');
    localStorage.removeItem('userinfo');
  }
}
</script>
